package com.m.config;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import com.m.security.UserLoginService;
import com.m.security.exceptions.AccessDeniedRtn;
import com.m.security.exceptions.AuthEntryPoint;
import com.m.security.filter.JWTAuthenticationFilter;
import com.m.security.filter.JWTLoginFilter;
import com.m.security.filter.LoginOutSecuessHandler;
import com.m.utils.PwdEncode;



/**
 * spring security的配置 ClassName: SecurityConfig Function: 一句话描述功能. auth: monxz
 * date: 2019年8月28日 上午10:04:50
 * 
 * @param <S>
 *
 *
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(99)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private UserLoginService loginService;

	// 登录执行的逻辑
	@Autowired
	public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(loginService).passwordEncoder(new PwdEncode());

	}

	// 配置信息
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		

		// 配置访问权限
		http.cors().and().csrf().disable().authorizeRequests()

				// 允许匿名访问(如api)
				.antMatchers("/mjob/**").permitAll().anyRequest().authenticated()

				// 配置jwt登陆以及处理
				.and().addFilter(new JWTLoginFilter(authenticationManager())) // 登录检验
				.addFilter(new JWTAuthenticationFilter(authenticationManager())) // token校验
				.exceptionHandling().accessDeniedHandler(new AccessDeniedRtn()) // 权限检验失败
				.authenticationEntryPoint(new AuthEntryPoint()) // token时效

				// 成功退出
				.and().logout().logoutUrl("/logout").logoutSuccessHandler(new LoginOutSecuessHandler());

		// 跨域以及其他的一些配置
		http.csrf().disable() // 关闭CSRF跨域
				.headers().frameOptions().sameOrigin(); // 允许加载frame子菜单

	}
	
	
	

}
